
package Controller;

import Model.Employee;
import Model.Mysql;
import Model.ResultSetTableModel;
import Model.ToExcel;
import View.AssistView;
import View.ListView;
import View.NewClient;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.IOException;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import net.sf.jxls.exception.ParsePropertyException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;


public class ControllerAssist implements ActionListener, PropertyChangeListener {
    
    private static AssistView view;
    private static Mysql mysql;
    private Employee employee;
    private static ResultSetTableModel tableModel;

    public ControllerAssist(AssistView view, Mysql mysql) {
        this.view = view;
        this.mysql = mysql;
        this.employee = new Employee(mysql); // instancio el constructor 
        
        
        //ActionPerformed
        view.getFieldCode().addActionListener(this);
        view.getButtonList().addActionListener(this);
        view.getButtonNew().addActionListener(this);
        view.getButtonExcel().addActionListener(this);
        
        
        // Fecha
        view.getDateChooser().setDate(Calendar.getInstance().getTime());
       
        
        // datos iniciales a la tabla 
        updateData();
        
        //PropertyChangeCalendar
         view.getDateChooser().addPropertyChangeListener(this);
         
         
        
    }
    
    
    
    
    
    
    
    public static void updateData(){
        try {
            
            Date date=(Date) view.getDateChooser().getDate(); 
            SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd"); 
            String fecha = format.format(date);
           
            tableModel = new ResultSetTableModel(" SELECT name, last, barcode, restaurant, departamento, date_beginning, assist FROM employee, assist where code_employee = employee.code and date_day = '"+fecha+"' group by employee.barCode ",mysql);
            view.getTableAssist().setModel(tableModel);
            
            view.getLabelCount().setText("Cantidad : "+tableModel.getRowCount());
            
        
        } catch (SQLException ex) {
            Logger.getLogger(ControllerAssist.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(ControllerAssist.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(ControllerAssist.class.getName()).log(Level.SEVERE, null, ex);
        }
        
    }

    @Override
    public void actionPerformed(ActionEvent ae) {
        
        Object whereIEnter = (Object) ae.getSource();
        
        if (whereIEnter == view.getFieldCode()){
            
            // si da enter en el campo del codigo de barra voy hacer lo siguieten 
            int codeBarIn = -1;
            
            try{
                codeBarIn = Integer.parseInt(view.getFieldCode().getText());
            }
            catch(Exception e){
                codeBarIn = -1; // esto quiere decir que no va hacer el valor 
            }
            
            
            
            codeBarIn = employee.isInList(codeBarIn); // Metodo que verifica si esta o no esta. 
            
            if (codeBarIn == -1){
                // No lo Encontro 
                
                   JOptionPane.showMessageDialog( view, "Lo siento, no existe ");
                   
                   
                   NewClient nc = new NewClient(mysql);
                   nc.setLocationRelativeTo(null);
                   nc.setVisible(true);
                   
                }   
            else {
                
                
                 // Message
        

                    //Custom button text
                    Object[] options = {"Continuar",
                                        "Modificar",
                                        "Cancelar"
                                    };
                    int opt = JOptionPane.showOptionDialog(view,
                        ""
                              + "Nombre : "+employee.getNombre()
                            + "\nApellido : "+employee.getApellido()
                            + "\nRestaurante : "+employee.getRestaurante()
                            + "\nDepartamento : "+employee.getDepartamento()
                            + "\nFecha de Inicio : "+employee.getDateB()
                            + "\nCodigo de Barra : "+employee.getCodigoBarra()
                        , 
                        "Confirmación de Datos ",
                        JOptionPane.YES_NO_CANCEL_OPTION,
                        JOptionPane.PLAIN_MESSAGE,
                        null,
                        options,
                        options[2]);





                    if(opt == 0){
                        
                          // voy a ingresar el dato 
                
                            Date date=(Date) view.getDateChooser().getDate(); 
                            SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd"); 
                            String fecha = format.format(date);

                            mysql.Query("INSERT INTO ASSIST (assist, code_employee, date_day) values (TRUE,"+codeBarIn+",'"+fecha+"')");


                        // Actualizo 

                            JOptionPane.showMessageDialog( null, "Listo, Ingrese ");
                            updateData(); // cambio los datos 

                    
                    }
                    else if(opt == 1){
                        
                        // Si modifico voy a ingresar y luego le tiro la ventana de modificar 
                         // voy a ingresar el dato 
                
                            Date date=(Date) view.getDateChooser().getDate(); 
                            SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd"); 
                            String fecha = format.format(date);

                            mysql.Query("INSERT INTO ASSIST (assist, code_employee, date_day) values (TRUE,"+codeBarIn+",'"+fecha+"')");


                        // Actualizo 

                            JOptionPane.showMessageDialog( null, "Listo, Ingrese ");
                            updateData(); // cambio los datos 
                            
                             NewClient va = new NewClient (mysql,codeBarIn);
                             va.setLocationRelativeTo(null);
                             va.setVisible(true);
                        
                        }
                    else if (opt == 2){
                        // No hago nada 
                    }

                }
           
            
            
            view.getFieldCode().setText("");
  
    }  
            
            
        
        else if (whereIEnter == view.getButtonList()){
           
               
                
                // boton para ir al listado 
                ListView viewList = new ListView();
                //Mysql
                ControllerList cController = new ControllerList(viewList,mysql);
                viewList.setLocationRelativeTo(null);
                viewList.setVisible(true);
           
        }
        
        else if (whereIEnter == view.getButtonNew()){
            
            // Nuevo  
                   
                   NewClient nc = new NewClient(mysql);
                   nc.setLocationRelativeTo(null);
                   nc.setVisible(true);
            
        }
        else if (whereIEnter == view.getButtonExcel()){
            try {
                
                
                // Fecha del Calendario 
                Date date=(Date) view.getDateChooser().getDate(); 
                
                
                
                // Creo mi objeto de tipo Excel 
                
                ToExcel exc = new ToExcel(mysql);
                exc.Employee("Employee",date);
                
                
                
            } catch (SQLException ex) {
                Logger.getLogger(ControllerAssist.class.getName()).log(Level.SEVERE, null, ex);
            } catch (ParsePropertyException ex) {
                Logger.getLogger(ControllerAssist.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(ControllerAssist.class.getName()).log(Level.SEVERE, null, ex);
            } catch (InvalidFormatException ex) {
                Logger.getLogger(ControllerAssist.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        
        
        
    }

    @Override
    public void propertyChange(PropertyChangeEvent pce) {
        if (pce.getSource() == view.getDateChooser()){
            updateData();
        }
    }
    
}
